import React, { Component } from 'react'


import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'

import styles from './index.module.css'

import { API } from '../../../../utils/api'

// 导入react-spring 动画库
import { Spring } from 'react-spring/renderprops'
// 标题的高亮状态
// true表示高亮，false表示不高亮
const titleSelectedStatus = { //对应的是标题栏的每一项
  area: false,
  mode: false,
  price: false,
  more: false
}

// 筛选条件的选中值
const selectedValues = {
  area: ['area', 'null'],
  mode: ['null'],
  price: ['null'],
  more: []
}

export default class Filter extends Component {
  state = {
    titleSelectedStatus,
    // 控制FilterPicker或FilterMore组件的展示和隐藏
    openType: '',
    //所有筛选条件数据
    filtersData: {},
    // 筛选条件的选中值
    selectedValues
  }

  componentDidMount() {

    // 获取到body
    this.htmlBody = document.body
    this.getFiltersData()
  }

  // 封装获取所有筛选条件的方法
  async getFiltersData() {
    // 获取当前城市的id
    const { value } = JSON.parse(localStorage.getItem('hkzf_city'))
    const { data: res } = await API.get(`/houses/condition?id=${value}`)
    // console.log(res);
    this.setState({
      filtersData: res.body
    })
  }

  // 高亮
  /**
   * 判断selectedValue中的值 是否为默认值
   * 如果type为area，此时，selectedVal.length !== 2 || selectedVal[0] !== 'area' 表示已经有选中值了
   * 如果type为mode，此时，selectedVal[0] !== 'null'，表示已经有选中值
   * 如果type为price，此时，selectedVal[0] !== 'null' ,就表示已经有选中值
   * 如果为more
   */

  // 点击标题菜单，切换高亮
  // 注意this指向的问题
  onTitleClick = (type) => {
    // 给body添加样式
    this.htmlBody.className = 'body-fixed'
    const { titleSelectedStatus, selectedValues } = this.state
    // 创建新的标题选中状态
    const newTitleSelectedStatus = { ...titleSelectedStatus }

    // 遍历标题选中状态对象
    Object.keys(titleSelectedStatus).forEach(key => {
      if (key === type) {
        // 当前点击标题
        newTitleSelectedStatus[type] = true
        return
      }
      // 其他标题
      const selectedVal = selectedValues[key]
      if (key === 'area' && (selectedVal.length !== 2 || selectedVal[0] !== 'area')) {
        // 高亮
        newTitleSelectedStatus[key] = true
      } else if (key === 'mode' && selectedVal[0] !== 'null') {
        newTitleSelectedStatus[key] = true
      } else if (key === 'price' && selectedVal[0] !== 'null') {
        newTitleSelectedStatus[key] = true
      } else if (key === 'more' && selectedVal.length !== 0) {
        // 更多选择项FilterMore组件
        newTitleSelectedStatus[key] = true
      } else {
        newTitleSelectedStatus[key] = false
      }
    })
    this.setState({
      openType: type,
      titleSelectedStatus: newTitleSelectedStatus
    })
  }
  // 取消（隐藏）对话框
  onCancel = (type) => {
    // 给body清除样式
    this.htmlBody.className = ''
    const { titleSelectedStatus, selectedValues } = this.state
    // 创建新的标题选中状态
    const newTitleSelectedStatus = { ...titleSelectedStatus }
    // 菜单高亮逻辑处理
    // 其他标题
    const selectedVal = selectedValues[type]
    if (type === 'area' && (selectedVal.length !== 2 || selectedVal[0] !== 'area')) {
      // 高亮
      newTitleSelectedStatus[type] = true
    } else if (type === 'mode' && selectedVal[0] !== 'null') {
      newTitleSelectedStatus[type] = true
    } else if (type === 'price' && selectedVal[0] !== 'null') {
      newTitleSelectedStatus[type] = true
    } else if (type === 'more' && selectedVal.length !== 0) {
      // 更多选择项FilterMore组件
      newTitleSelectedStatus[type] = true
    } else {
      newTitleSelectedStatus[type] = false
    }
    this.setState({
      openType: '',
      // 更新菜单高亮状态数据
      titleSelectedStatus: newTitleSelectedStatus
    })
  }

  // 确定（隐藏）对话框
  onSave = (type, value) => {
    // 给body清除样式
    this.htmlBody.className = ''
    const { titleSelectedStatus } = this.state
    // 创建新的标题选中状态
    const newTitleSelectedStatus = { ...titleSelectedStatus }
    // 菜单高亮逻辑处理
    // 其他标题
    const selectedVal = value
    if (type === 'area' && (selectedVal.length !== 2 || selectedVal[0] !== 'area')) {
      // 高亮
      newTitleSelectedStatus[type] = true
    } else if (type === 'mode' && selectedVal[0] !== 'null') {
      newTitleSelectedStatus[type] = true
    } else if (type === 'price' && selectedVal[0] !== 'null') {
      newTitleSelectedStatus[type] = true
    } else if (type === 'more' && selectedVal.length !== 0) {
      // 更多选择项FilterMore组件
      newTitleSelectedStatus[type] = true
    } else {
      newTitleSelectedStatus[type] = false
    }

    //  获取到最新的数据
    const newSelectedValues = {
      ...this.state.selectedValues,
      // 只更新当前type对应的值
      [type]: value
    }

    // 分别获取得到选中的数据
    const { area, mode, price, more } = newSelectedValues

    // 筛选条件数据，是一个对象
    const filters = {}

    // 区域,他的值分为两种情况 area和subway
    const areaKey = area[0]
    let areaValue = 'null'
    if (area.length === 3) {
      areaValue = area[2] === 'null' ? area[1] : area[2]
    }
    filters[areaKey] = areaValue

    // 方式和租金
    filters.mode = mode[0]
    filters.price = price[0]

    // 更多筛选条件 more
    filters.more = more.join(',')

    // 调用父组件方法，将筛选后的数据传递给父组件
    this.props.onFilter(filters)

    this.setState({
      openType: '',
      selectedValues: newSelectedValues,
      // 更新菜单高亮状态数据
      titleSelectedStatus: newTitleSelectedStatus
    })
  }

  // 渲染FilterPicker组件方法
  renderFilterPicker() {
    const { openType, filtersData: { area, subway, rentType, price }, selectedValues } = this.state
    if (openType !== 'area' && openType !== 'mode' && openType !== 'price') {
      return null
    }
    // 根据openType来筛选条件数据
    let data = []
    // 展示的列数
    let cols = 3
    // 默认值
    let defaultValue = selectedValues[openType]
    switch (openType) {
      case 'area':
        // 获取到区域数据
        data = [area, subway]
        cols = 3
        break;
      case 'mode':
        // 获取到方式数据
        data = rentType
        cols = 1
        break;
      case 'price':
        // 获取到价格数据
        data = price
        cols = 1
        break;
      default:
        break;
    }
    return <FilterPicker
      key={openType}
      onCancel={this.onCancel}
      onSave={this.onSave}
      data={data} cols={cols}
      type={openType}
      defaultValue={defaultValue} />
  }

  // 渲染FilterMore组件方法
  renderFilterMore() {
    const { openType, filtersData: { roomType, oriented, floor, characteristic }, selectedValues } = this.state
    if (openType !== 'more') {
      return null
    }
    const data = {
      roomType, oriented, floor, characteristic
    }
    // 将默认值传递给子组件
    const defaultValue = selectedValues[openType]
    return <FilterMore data={data} type={openType} onSave={this.onSave} defaultValue={defaultValue} onCancel={this.onCancel} />
  }

  // 渲染遮罩层div
  renderMask() {
    const { openType } = this.state
    // 根据opcity的值来进行修改
    const isHide = openType === 'more' || openType === ''

    return (<Spring from={{ opacity: 0 }} to={{ opacity: isHide ? 0 : 1 }}>
      {props => {
        // 证明完成了图像的遮罩，返回一个null
        if(props.opacity ===0){
          return null
        }
        return (<div style={props} className={styles.mask} onClick={() => this.onCancel(openType)}></div>)
      }
      }
    </Spring>)

    // if (openType === 'more' || openType === '') {
    //   return null
    // }
    // return (<Spring from={{ opacity: 0 }} to={{ opacity: 1 }}>
    //   {props => <div style={props} className={styles.mask} onClick={() => this.onCancel(openType)}></div>}
    // </Spring>
    // )
  }

  render() {
    const { titleSelectedStatus, openType } = this.state
    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}
        {this.renderMask()}

        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle titleSelectedStatus={titleSelectedStatus} onClick={this.onTitleClick} />

          {/* 前三个菜单对应的内容： */}
          {
            this.renderFilterPicker()
          }

          {/* 最后一个菜单对应的内容： */}
          {this.renderFilterMore()}
        </div>
      </div>
    )
  }
}
